package com.xuebang.admin.util;

import java.util.Map;

import javax.inject.Inject;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;

/**
 * 邮件发送器
 */
/*@Component*/
public class MailSender {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	private JavaMailSender javaMailSender;
	private VelocityEngine velocityEngine;

	@Inject
	public MailSender(JavaMailSender javaMailSender,
			VelocityEngine velocityEngine) {
		this.javaMailSender = javaMailSender;
		this.velocityEngine = velocityEngine;
	}

	public boolean send(String from, String subject, String to,
			Map<String, Object> model, EmailType emailType) {
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg);

		try {
			helper.setFrom(from);
			helper.setSubject(subject);
			helper.setTo(to);
			// 判断email类型
			if ((EmailType.HTML).equals(emailType)) {
				helper.setText(getHtmlContent(model), true);
			} else if (EmailType.TEXT.equals(emailType)) {
				helper.setText(getTextContent(model));
			}
			javaMailSender.send(msg);
		} catch (MessagingException e) {
			logger.warn("邮件信息导常! 邮件标题为: " + subject);
			return false;
		} catch (MailException me) {
			logger.warn("发送邮件失败! 邮件标题为: " + subject);
			return false;
		}
		return true;
	}

	/**
	 * 邮件模板中得到信息
	 * 
	 * @return 返回特发送的内容
	 */
	private String getHtmlContent(Map<String, Object> model) {
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
				"email/alert_html.vm", "UTF-8", model);
	}

	private String getTextContent(Map<String, Object> model) {
		return VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
				"email/alert_text.vm", "UTF-8", model);
	}

	/**
	 * EmailType
	 */
	public enum EmailType {
		HTML, TEXT;
		private EmailType() {
		}
	}
}